<template>
  <div class="category-edit-container" >
    <div class="fe-page-header">
      <div class="fe-page-header__left">
        {{ action == 'edit' ? $t('common.pageTitle.pagePartCategoryEdit') : $t('common.pageTitle.pagePartCategoryCreate') }}
      </div>
      <div class="fe-page-header__right">
        <FormCellChange class="mar-r-8" :count="formCellCount" @update="(e)=>{formCellCount=e}"></FormCellChange>
        <el-button type="plain-third"  @click="back">{{$t('common.base.back')}}</el-button>
        <el-button type="primary" @click="validate" :disabled="pending" v-if="allowEdit">{{$t('common.base.save')}}</el-button>
      </div>
    </div>
  
    <div class="category-edit-view">
      <div class="category-edit-content bbx-cell-form-builder">
        <el-form label-position="top" :model="part" :rules="rules" ref="partForm" :inline-message="true" class="category-builder-change" :class="[formBuilderClass, {'change-cell': formCellCount > 1}]">
          <el-form-item :label="`${$t('common.base.serialNumber')}：`" prop="serialNumber" class="bbx-form-cell-item">
            <el-input style="width: 66.6666667%" v-model.trim="part.serialNumber" :placeholder="$t('part.edit.text1', {count: 50})"></el-input>
          </el-form-item>
          <el-form-item :label="`${$t('common.base.name')}：`" prop="name" class="bbx-form-cell-item">
            <el-input style="width: 66.6666667%"  v-model="part.name" :placeholder="$t('part.edit.text2', {count: 255})"></el-input>
          </el-form-item>
          <el-form-item :label="`${$t('common.form.preview.serviceItem.colum3')}：`" prop="type" class="bbx-form-cell-item">
            <el-select style="width: 66.6666667%" v-model="part.type" :placeholder="$t('part.list.text7')">
              <el-option :label="item" :value="item" v-for="item in types" :key="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="`${$t('common.form.preview.sparepart.label3')}：`" prop="standard"  class="bbx-form-cell-item">
            <el-input style="width: 66.6666667%" v-model="part.standard" :placeholder="$t('part.edit.text3', {count: 500})"></el-input>
          </el-form-item>
          <el-form-item :label="`${$t('common.form.preview.serviceItem.colum4')}：`" prop="unit" class="bbx-form-cell-item">
            <el-select style="width: 66.6666667%" v-model="part.unit" :placeholder="$t('part.edit.text4')">
              <el-option :label="item" :value="item" v-for="item in units" :key="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="`${$t('product.component.miniTable.partType.salePrice')}：`" prop="salePrice" class="bbx-form-cell-item">
            <el-input style="width: 66.6666667%" v-model.number="part.salePrice" @blur="numeric('salePrice', $event)" @input="filterNumber($event, 'salePrice')" :placeholder="$t('part.edit.text5')"></el-input>
          </el-form-item>
          <el-form-item :label="`${$t('product.component.miniTable.partType.costPrice')}：`" prop="costPrice" class="bbx-form-cell-item">
            <el-input style="width: 66.6666667%" v-model.number="part.costPrice" @blur="numeric('costPrice', $event)" @input="filterNumber($event, 'costPrice')" :placeholder="$t('part.edit.text6')"></el-input>
          </el-form-item>
          <el-form-item :label="`${$t('common.base.explain')}：`" prop="description" class="bbx-form-cell-item">
            <div class="auto" ref="textareaRef">
              <el-input style="width: 66.6666667%" type="textarea" :placeholder="$t('part.edit.text7')" @input="input" v-model="part.description"></el-input>
            </div>
          </el-form-item>
          <el-form-item :label="`${$t('common.base.image')}：`" :class="['category-edit-form-item-upload', attachments.length >= 9 ? 'hide_box' : '']" class="bbx-form-cell-item">
<!--            <base-upload style="width: 66.6666667%" :value="attachments" @input="uploadImg" :limit="9" accept="image/*">
              <template slot="preview">
                <div class="part-image-preview" v-show="partImg">
                  <img :src="partImg" @click="preview(partImg)">
                  <button type="button" @click.stop="removePartImg" class="part-image-close"><i class="el-icon-circle-close"></i></button>
                </div>
              </template>
            </base-upload>
            <div class="image-hint font-12 color-999">
              建议尺寸：375X375 像素（尺寸偏差大时，影响图片在手机上的显示效果），最多上传9张
            </div>-->
            <biz-cropper-upload
              action="string"
              list-type="picture-card"
              accept="image/*"
              :on-preview="handlePictureCardPreview"
              :http-request="UploadImagePic"
              :before-upload="onBeforeUploadImage"
              :file-list="categoryPics"
              :on-exceed="onExceedPic"
              :on-remove="onRemovePic"
              @cropperDone="picCropperDone"
              multiple
              :limit="9"
              :tips="$t('part.edit.text8', {px: '375X375', maxCount: 9})"
              :cropper="{
                autoCropWidth: 375,
                autoCropHeight: 375,
                fixedNumber: [375, 375]
              }"
            ></biz-cropper-upload>
          </el-form-item>
          <el-form-item v-if="ifCatalogPathIdsShow" :label="`${$t('common.form.type.related_catalog')}：`" class="bbx-form-cell-item">
            <el-cascader
              :placeholder="$t('common.placeholder.selectProductType')"
              popperClass='cascader-checkbox'
              v-model="part.catalogPathIds"
              :options='catalogOption'
              :show-all-levels="false"
              expand-trigger="hover"
              clearable
              :props="catalogCascaderProps"
              filterable
              collapse-tags
            ></el-cascader>
            <el-tooltip
              placement="top"
              :content="$t('part.edit.text9')">
              <i class="el-icon-question el-tooltip"></i>
            </el-tooltip>
          </el-form-item>
        </el-form>
      </div>
    </div>  
  </div>
</template>

<script>
import BaseGallery from 'packages/BaseGallery/index';
import qs from '@src/util/querystring2';
import AuthUtil from '@src/util/auth';
import _ from 'lodash';
/* enum */
import TenantDataLimitSourceEnum from '@model/enum/TenantDataLimitSourceEnum'
import TenantDataLimitTypeEnum from '@model/enum/TenantDataLimitTypeEnum'
/* mixin */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import ThemeMixin from '@src/mixins/themeMixin/index.ts'

import {Cascader} from 'element-ui';
import {cloneData} from '@src/api/ProductV2Api';
import Uploader from 'packages/BaseUpload/uploader';
import { RESOURCE_PREFIX } from '@src/util/linkSwitch'; 
/* components */
import FormCellChange from '@src/component/compomentV2/FormCellChange'

export default {
  name: 'partV2-edit-view',
  inject: ['initData'],
  mixins: [VersionMixin, ThemeMixin],
  components:{
    [Cascader.name]: Cascader,
    [FormCellChange.name]: FormCellChange
  },
  data() {
    return {
      getFirstHeightStatus: true, // 第一次获取textarea默认高度状态控制
      getHeight: 0, // 获取textarea的高度
      formCellCount: 1,
      auths: {},
      action: 'create',
      units: [],
      types: [],
      pending: false,
      attachments: [],
      categoryPics: [],
      origin: {},
      
      part: {
        id: '',
        serialNumber: '',
        name: '',
        standard: '',
        type: '',
        description: '',
        unit: '',
        image: '',
        salePrice: '',
        costPrice: '',
        catalogPathIds: []
      },
      rules: {
        serialNumber: [
          {required: true, message: this.$t('part.edit.text10')},
          {max: 50, message: this.$t('part.edit.text11', {maxCount: 50})},
          {validator: _.debounce((rule, value, callback) => {
            value = value && value.trim();
            
            let err = [];
            if(this.action == 'edit' && value == this.origin.serialNumber) return callback(err)
            
            this.$http.post('/partV2/category/checkUnique', {field: 'serialNumber',value: value}, false)
              .then(result => {
                if(result.status != 0) err.push(new Error(this.$t('part.edit.text12')))
              })
              .catch(err => console.warn(err))
              .finally(() => callback(err))
          }, 500)}
        ],
        name: [
          {required: true, message: this.$t('part.edit.text13')},
          {max: 255, message: this.$t('part.edit.text14', {maxCount: 255})}
        ],
        type: [
          {required: true, message: this.$t('part.edit.text15')},
        ],
        standard: [
          {required: true, message: this.$t('part.edit.text16')},
          {max: 500, message: this.$t('part.edit.text17', {maxCount: 500})}
        ],
        salePrice: [
          {
            validator: (rule, value, callback) => {
              const val = Number(value);
              if (value === '') {
                callback(new Error(this.$t('part.edit.text18')))
              } else if(val < 0 || isNaN(val)){
                callback(new Error(this.$t('part.edit.text19', {num: 0})))
              } else{
                callback();
              }
            },
            trigger: 'change',
            required: true
          }
        ],
        costPrice: [
          {
            validator: (rule, value, callback) => {
              const val = Number(value);
              if (value === '') {
                callback(new Error(this.$t('part.edit.text18')))
              } else if(val < 0 || isNaN(val)){
                callback(new Error(this.$t('part.edit.text19', {num: 0})))
              } else{
                callback();
              }
            },
            trigger: 'change',
            required: true
          }
        ],
        description:[
          {max: 2000, message: this.$t('part.edit.text20', {count: 2000})}
        ]
      },

      catalogOption:[],
      catalogCascaderProps: {
        multiple:true,
        value:'id',
        label:'name',
        children:'tasks',
      }
    }; 
  },
  computed: {
    formBuilderClass() { 
      let baseClass = ['form-builder']
      if (this.formCellCount > 1) {
        // 多列布局
        baseClass = [...baseClass, `bbx-cell-form-box-${this.formCellCount}`, 'bbx-cell-form-box']
      }
      return baseClass
    },
    /**
     * @description 获取表单dom
     */
     textareaRef() {
      return this.$refs.textareaRef.querySelector('textarea');
    },
    getTextareaGrpa() {
      return this.$refs.textareaRef.parentElement.parentElement;
    },
    partImg(){
      if(!this.attachments || this.attachments.length == 0) return null;

      if(Array.isArray(this.attachments) && this.attachments.length > 0) {
        return this.attachments.map(item => {
          return {
            id: item.id || '',
            fileSize: item.fileSize || '',
            fileName: item.filename || item.fileName || '',
            status: item.status || '',
            uid: item.uid || '',
            url: item.url || ''
          }
        });
      }else {
        return this.attachments[0].url;
      }
    },
    allowEdit(){
      return this.action == 'create' ? AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_CREATE') : AuthUtil.hasAuth(this.auths, 'VIP_SPAREPART_EDIT')
    },
    ifCatalogPathIdsShow() {
      return this.initData?.openSuperCodePro
    }
  },
  methods: {
    input() {
      this.autoResize()
    },
    autoResize() {
      if (this.getFirstHeightStatus) {
        this.getHeight = this.textareaRef.offsetHeight;
        this.getFirstHeightStatus = false
      }
      const defaultHeight = this.getHeight
      const maxHeight = 320
      this.textareaRef.style.height = `${defaultHeight}px`;
      this.getTextareaGrpa.style.height = `${defaultHeight + 30}px`;
      const contentHeight = this.textareaRef.scrollHeight;
      if (contentHeight > defaultHeight && contentHeight <= maxHeight) {
        this.textareaRef.style.height = `${contentHeight}px`;
        this.getTextareaGrpa.style.height = `${contentHeight + 30}px`;
        this.textareaRef.style.overflowY = 'hidden';
      } else if (contentHeight > maxHeight) {
        this.textareaRef.style.height = maxHeight + 'px';
        this.getTextareaGrpa.style.height = maxHeight + 30 + 'px';
        this.textareaRef.style.overflowY = 'auto';
      } else {
        this.textareaRef.style.height = defaultHeight + 'px';
        this.getTextareaGrpa.style.height = defaultHeight + 30 + 'px';
      }
    },
    // 预览图片
    handlePictureCardPreview (file) {
      let urls = this.attachments.map((item) => {
        return item.url
      });
      this.$previewElementImg(file.url, urls)
    },
    /**
     * @description: 获取上传文件
     * @param {Object} param el-upload 返回的文件格式
     * @param {Boolean} isNeedUpload 是否需要调用上传接口
     * @param {Object} files isNeedUpload 则需要带上files
     * @return {Object} file
     */
    async handleGetFile(param, isNeedUpload = true, files) {
      let file = files;
      if(isNeedUpload) {
        const result = await Uploader.upload(param.file, '/files/upload')
        if (result.status !== 0) {
          this.$message({
            message: `${result.message}`,
            duration: 1500,
            type: 'error',
          });
          return null;
        }
        file = result.data;
      }
      return !file ? null :  {
        uid: param.file.uid,
        id: file.id,
        filename: file.fileName,
        // 如果后端返回url,必须使用。如果后端不返回，需要拼接
        url: file.ossUrl || file.url || `/files/get?fileId=${file.id}`,
        fileSize: file.fileSizeStr,
      };
    },
    // 移除file
    onRemovePic(file, fileList) {
      this.attachments = this.attachments.filter(item => item.uid !== file.uid)
    },
    onExceedPic () {
      this.$message.error(this.$t('part.edit.text21', {max: 9}));
    },
    async picCropperDone(beforeFile, afterFile) {
      const result = await this.handleGetFile({file: beforeFile}, false, afterFile);
      if (result) {
        this.attachments.push(result);
      }
    },
    async UploadImagePic (param) {
      const file = await this.handleGetFile(param);
      if(file) {
        this.attachments.push(file)
      }
    },
    onBeforeUploadImage (file) {
      console.log('file')
    },
    preview(url){
      this.$previewElementImg(url)
      // BaseGallery.preview(event.target)
    },
    uploadImg(attachments){
      this.attachments = attachments;
    },
    async removePartImg(){
      if(await this.$platform.confirm(this.$t('part.edit.text22'))) this.attachments = [];
    },
    numeric(field, event){
      let value = this.part[field];
      this.part[field] = '';
      this.$nextTick(() => this.part[field] = value);
    },
    filterNumber(value, field) {
      if(!value) return;
      let reg = /^[0-9]+([.]{1}[0-9]{0,2}){0,1}$/;
      let num = reg.test(value) ? value : (isNaN(Number(value)) ? value : Number(value).toFixed(3).slice(0, -1));
      this.$nextTick(() => this.part[field] = num);
    },
    validate() {
      if(this.pending) return;

      this.pending = true; 

      this.$refs.partForm.validate((valid) => {
        if(valid) {
          this.submit(this.part)
        } else {
          this.pending = false;
        }
      })
    },
    back(){
      window.history.back()
    },
    async submit(part){
      if(!this.allowEdit) return;
      
      let loading = this.$loading();
      this.pending = true;

      try {
        if(this.partImg) {
          if(Array.isArray(this.partImg)) {
            part.imageGroup = this.partImg;
            part.imageList =  this.partImg.map(item => item.url);
            part.image = null;
          }else {
            part.image = this.partImg;
          }
        }
        part.catalogIds = part.catalogPathIds.map(item=>item[item.length-1]);

        let url = this.action == 'edit' ? '/partV2/category/update' : '/partV2/category/create';
        const SubmitPromise = this.$http.post(url, part)
        let result = await this.checkNumExceedLimitAfterHandler(SubmitPromise)
        
        if(result.status == 0){
          if(this.action == 'edit'){
            window.location.href = `${this.$resourcePrefix}/partV2/category/detail?id=${part.id}`
          }else{
            window.location.href = `${this.$resourcePrefix}/partV2/category/list`
          }
         
        } else{
          this.$platform.alert(result.message)
        }
      } catch (error) {
        console.warn(error)
      }

      loading.close();
      this.pending = false;
    },
    initialize(origin){
      let part = this.part;

      part.id = origin.id || '';
      part.serialNumber = origin.serialNumber || '';
      part.name = origin.name || ''
      part.standard = origin.standard || '';
      part.type = origin.type || '';
      part.description = origin.description || '';
      part.unit = origin.unit || '';
      part.salePrice = origin.id ? origin.salePrice : '';
      part.costPrice = origin.id ? origin.costPrice : '';
      part.catalogIds = origin.catalogIds || []
      part.catalogPathIds = origin.catalogPathIds || []

      if(origin.image){
        this.attachments = [{
          url: origin.image
        }]
      }

      if(this.units.length > 0 && !origin.unit) part.unit = this.units[0]; 
      if(this.types.length > 0 && !origin.type) part.type = this.types[0]; 
    },
    fetchData(id){
      if(!id) return Promise.all({});

      return this.$http.get('/partV2/category/get', {id})
    },
    // 获取树结构
    async getCatalogOption () {
      try{
        let {code,result,message} = await cloneData();
        if(code === 0) {
          this.deleteEmpty(result);
          this.catalogOption = result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty (list) {
      list.forEach(item => {
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    }
  },
  async mounted(){
    try {
      let initData = this.initData;
      this.units = initData.units || [];
      this.types = initData.sparepartType || [];
      this.auths = initData.auths;

      let path = window.location.pathname;
      if(path.indexOf(RESOURCE_PREFIX) > -1) path = path.replace(RESOURCE_PREFIX, '')
      if(path == '/partV2/category/edit') this.action = 'edit'; 

      let part = {};

      if(this.action == 'edit'){
        let urlParams = qs.parse(window.location.search);
        let loading = this.$loading();
        let result = await this.fetchData(urlParams.id);
        loading.close();
        if(result.imageGroup && Array.isArray(result.imageGroup) && result.imageGroup.length > 0){
          result.imageGroup.forEach(item => {
            this.attachments.push(item)
          });
          this.categoryPics = this.attachments;
        }
        if(result.imageList && Array.isArray(result.imageList) && result.imageList.length > 0){
          result.image = "";
          result.imageList.forEach(url => {
            let enable = this.attachments.every(image => image.url !== url);
            if(enable) {
              let obj = {};
              obj.url = url;
              this.attachments.push(obj);
            }
          });
          this.categoryPics = this.attachments;
        }
        part = result || {};
      } else {
        // 检查版本数量限制
        this.checkNumExceedLimitBeforeHandler
        && this.checkNumExceedLimitBeforeHandler(
          TenantDataLimitSourceEnum.SparePart,
          TenantDataLimitTypeEnum.SparePart
        )
      }

      this.initialize(part);
      this.origin = part;
    } catch (error) {
      console.warn(error)
    }
    this.getCatalogOption()
  }
}
</script>
<style lang="scss">
body {
  padding: 12px;
}
</style>
<style lang="scss" scoped>
.category-edit-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  border-radius: 4px;
  .category-edit-view {
    height: calc(100% - 56px);
    overflow: auto;
    padding: 16px;
    .el-form-item {
      margin: 10px;
    }
  }
}
.change-cell.change-cell {
  .el-form-item {
    margin: 0px 12px 10px 0;
  }
}
.page-panel{
  margin-bottom: 0;
  border-bottom: 1px solid #f4f7f5;
  &:first-child {
    border-radius: 4px 4px 0 0;
  }
  &:last-child {
    border-radius: 0 0 4px 4px;
  }
}
.part-image-preview {
  position: relative;
  width: 128px;
  max-height: 128px;
  cursor: pointer;
  overflow: hidden;

  img{
    display: block;
    max-width: 100%;
    max-height: 100%;
  }

  .part-image-close{
    position: absolute;
    top: 5px;
    right: 5px;
    border: none;
    outline: none;
    background-color: transparent;
    padding: 0;
    cursor: pointer;

    color: #F56C6C;
    font-size: 16px;
    display: none;
  }

  &:hover{
    .part-image-close{
      display: block;
    }
  }
}

.category-edit-form-item-upload {
  margin-top: 10px;
  .image-hint {
    width: 66.6666667%;
    margin-top: 5px;
    height: 20px;
    line-height: 20px;
  }
  ::v-deep.el-upload-list__item {
    transition: none !important;
  }
  ::v-deep .el-upload--picture-card {
    width: 80px;
    height: 80px;
    line-height: 80px;
    margin-bottom: 6px;
    &:hover {
      border-color: $color-primary;
    }
  }
  ::v-deep .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}
.hide_box ::v-deep .el-upload--picture-card {
  display: none;
}

::v-deep .el-cascader {
  width: 66.6666667%;
  .el-cascader__search-input {
    margin: 2px 0 2px 12px;
  }
}
</style>
<style lang="scss">
  .cascader-checkbox .el-cascader-node__label {
    max-width: 200px;
  }
  .el-icon-question {
    vertical-align: middle;
    color: #666;
    font-size: 16px;
  }
</style>
<style lang="scss">
.category-builder-change.change-cell {
  margin: 0;
  padding: 0;
  max-width: initial;
  .bbx-form-cell-item {
    .el-form-item__content {
      height: 65px;
      > div:first-child {
        width: 100%!important;
      }
      .auto {
        > div:first-child {
          width: 100%!important;
        }
      }
      .el-cascader.el-cascader {
        width: calc(100% - 22px)!important;
      }
    }
  }
}
</style>